package protobuffer;

import protobuffer.PersonOuterClass.Person;

import java.io.*;

public class ProtoBuffer {
    public static void main(String[] args) {

        serialize();
        deserialize();

        //对比java 的序列化
        javaSerialize();
        javaDeserialize();
    }

    private static void javaDeserialize() {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("src/java_file_person")) {

            };

            People people = (People) objectInputStream.readObject();
            System.out.println(people.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void javaSerialize() {
        People people = new People("hentex", "hentex@gmail.com", 1334);
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("src/java_file_person")) {

            };
            objectOutputStream.writeObject(people);
            objectOutputStream.flush();
            objectOutputStream.close();
            System.out.println("java 序列化文件大小：" + new File("src/java_file_person").length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void serialize() {
        Person hentex = Person.newBuilder()
                .setId(1334)
                .setEmail("hentex@gmail.com")
                .setName("hentex")
                .build();


        try {
            hentex.writeTo(new FileOutputStream("src/protobuff_file_person"));
            System.out.println("protobuf 序列化文件大小： " + new File("src/protobuff_file_person").length());
        } catch (IOException e) {
            e.addSuppressed(new Exception("File Not Found in supplied path "));
            e.printStackTrace();
        }
    }

    private static void deserialize() {
        try {
            FileInputStream stream = new FileInputStream("src/protobuff_file_person");
            System.out.println(stream.available());
            Person person = Person.parseFrom(stream);
            System.out.println(person.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
